package com.itxiuyixiu.homework.utils.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 黄磊
 * @date 2020/4/11
 */
@Component
public class String2LocalDateConverter implements Converter<String, LocalDate> {
    @Autowired
    private ConverterRegistry converterRegistry;

    @Bean
    public void addString2LocalDateConverter() {
        converterRegistry.addConverter(new String2LocalDateConverter());
    }

    @Override
    public LocalDate convert(String s) {
        LocalDate time;
        try {
            time = LocalDate.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } catch (Exception e) {
            e.printStackTrace();
            time = null;
        }
        return time;
    }
}
